package com.tourism.tourismGYM.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.tourism.tourismGYM.commom.BasePage;
import com.tourism.tourismGYM.dao.TourismRmDao;
import com.tourism.tourismGYM.entity.TourismApm;
import com.tourism.tourismGYM.entity.TourismRm;
import com.tourism.tourismGYM.service.TourismApmService;
import com.tourism.tourismGYM.service.TourismRmService;
@Service
@Transactional
public class TourismRmServiceImpl implements TourismRmService {
	@Autowired
	private TourismRmDao tourismRmDao;
	@Autowired
	private TourismApmService tourismApmService;
	@Override
	public List<TourismRm> getByApmId(String id) {
		// TODO Auto-generated method stub
		return tourismRmDao.getByApmId(id);
	}

	@Override
	public Page<TourismRm> page(Map<String, Object> condition) {
		BasePage basePage = new BasePage(condition);
		String applicant ="";
		Pageable pageable = basePage.getPageable("applicationTime");
		if(condition.containsKey("applicant")&& !condition.get("applicant").equals("")) {
			applicant =condition.get("applicant").toString();
		}
		Page<TourismRm> results = tourismRmDao.findPage(applicant,pageable);
		if(results.getSize()>0) {
			for (TourismRm t : results) {
				TourismApm tourismApm = tourismApmService.getById(t.getApmId());
				if(tourismApm != null) {
					t.setApmName(tourismApm.getActiveName());
				}
			}
		}
		return results;
	}

	@Override
	public boolean delete(String id) {
		TourismRm tourismRm = tourismRmDao.findOne(id);
		TourismApm tourismApm = tourismApmService.getById(tourismRm.getApmId());
		int number =  tourismApm.getApplicantNumber()-tourismRm.getNumbers();
		if(number <0) {
			number = 0;
		}		
		tourismApm.setApplicantNumber(number);
		tourismApmService.create(tourismApm);
		tourismRmDao.delete(id);
		return true;
	}

	@Override
	public TourismRm create(TourismRm tourismRm) {
		tourismRm.setApplicationTime(new Date());
		TourismApm tourismApm = tourismApmService.getById(tourismRm.getApmId());
		tourismApm.setApplicantNumber(tourismApm.getApplicantNumber()+tourismRm.getNumbers());
		tourismApmService.create(tourismApm);
		return tourismRmDao.save(tourismRm);
	}

	@Override
	public List<TourismRm> getAll() {
		// TODO Auto-generated method stub
		return tourismRmDao.findAll();
	}
}
